/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.cjb.malacma.rssfeed.util;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import net.cjb.malacma.rssfeed.entity.FeedUrl;

/**
 *
 * @author malacma
 */
public class PersistenceUtil {

    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("PinoRSSPU");

    public static void persist(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            em.close();
        }
    }

    public static FeedUrl getLastFeedUrl() {
        EntityManager em = emf.createEntityManager();
        FeedUrl fu = null;
        try {
            em.getTransaction().begin();
            List<FeedUrl> fuList = (List<FeedUrl>) em.createQuery("select u from FeedUrl u").getResultList();
            int size = fuList.size();
            int pos = (int)((Math.random()+1)*size/2);
            fu = fuList.get(pos);
            fuList = null;
        } finally {
            em.close();
            return (fu == null ? new FeedUrl() : fu);
        }
    }

    public static List<FeedUrl> findAllFeedUrl() {
        EntityManager em = emf.createEntityManager();
        List<FeedUrl> fu = new ArrayList<FeedUrl>();
        try {
            em.getTransaction().begin();
            fu = (List<FeedUrl>) em.createQuery("select u from FeedUrl u").getResultList();
        } finally {
            em.close();
            return fu;
        }
    }

    public static List<FeedUrl> findOffLineFeeds() {
        EntityManager em = emf.createEntityManager();
        List<FeedUrl> fu = new ArrayList<FeedUrl>();
        try {
            em.getTransaction().begin();
            fu = (List<FeedUrl>) em.createNamedQuery("offLineFeeds").getResultList();
        } finally {
            em.close();
            return fu;
        }
    }

   public static void merge(Object f1) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(f1);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
}
